package com.jungle.framework.chat;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.jungle.common.enums.HttpMethod;
import com.jungle.framework.config.properties.ChatProperties;
import com.jungle.framework.config.properties.DevProxyProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
@RequiredArgsConstructor
public class OpenAiApi {
    private final ChatProperties chatConfig;

//    private static final MultiThreadedHttpConnectionManager CONNECTION_MANAGER= new MultiThreadedHttpConnectionManager();
//
//    static {
//        // 默认单个host最大链接数
//        CONNECTION_MANAGER.getParams().setDefaultMaxConnectionsPerHost(
//                Integer.valueOf(20));
//        // 最大总连接数，默认20
//        CONNECTION_MANAGER.getParams()
//                .setMaxTotalConnections(20);
//        // 连接超时时间
//        CONNECTION_MANAGER.getParams()
//                .setConnectionTimeout(60000);
//        // 读取超时时间
//        CONNECTION_MANAGER.getParams().setSoTimeout(60000);
//    }

    public ChatExecuteRes get(String path, Map<String, String> headers) {
        return null;
    }

    /**
     * 获取所有可以用模型
     *
     * @param path 接口路径
     * @return
     */
    public ChatExecuteRes getAllModel(String path) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url(chatConfig.getUrl() + path)
            .addHeader("Authorization", "Bearer " + chatConfig.getToken())
            .build();
        try (Response response = client.newCall(request).execute()) {
            ResponseBody resultBody = response.body();
            if (response.isSuccessful()) {
                log.info("Char 获取所有可以用模型");
            } else {
                throw new RuntimeException("获取OpenAI模型异常" + response.message());
            }
            return new ChatExecuteRes(true, resultBody.string(), null, 200);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static final MediaType JSON = MediaType.get("application/json");

    @Value("${spring.profiles.active}")
    private String env;

    private final DevProxyProperties devProxyProperties;
    /**
     * 调用CharGPT聊天接口
     *
     * @param path       接口路径
     * @param userDialog 用户对话内容
     * @return
     */
    public ChatExecuteRes post(String path, String userDialog) {
        ChatMessage chatMessage = new ChatMessage("user", userDialog);
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(chatMessage);
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
            .model("gpt-3.5-turbo")
            .messages(messages)
            .build();
        String url = chatConfig.getUrl() + path;
        log.info("Chat 请求地址:{}", url);
        HttpRequest request = HttpRequest.post(url)
            .body(JSONUtil.toJsonStr(chatCompletionRequest))
            .header("Authorization", "Bearer " + chatConfig.getToken());
        if ("dev".equals(env)) { //本地环境使用代理
            request.setHttpProxy(devProxyProperties.getIp(), devProxyProperties.getPort());
        }
        HttpResponse response = request.execute();
        log.info("Char Post请求");
        return new ChatExecuteRes(true, response.body(), HttpMethod.POST, 200);
    }
}
